#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "PF_UTIL.h"
#include "simparameters.h"


FPOINT_PTR CreateFP(char InChar[]){
    //Allocate the Floating Point in the memory
    int i,j;
    FPOINT_PTR Created_FP=(FPOINT_PTR) FPmalloc(sizeof(FPOINT));
    Created_FP->sign=InChar[0];
    for(i=1;i<EXPONENT_WIDTH+1;i++){
        Created_FP->Exponent[i-1]=InChar[i];
    }
    Created_FP->Exponent[EXPONENT_WIDTH+1]='\0';
    for(j=EXPONENT_WIDTH+1;j<(EXPONENT_WIDTH+1+FRACTION_WIDTH);j++){
        Created_FP->Fraction[j-1-EXPONENT_WIDTH]=InChar[j];
    }

    Created_FP->Fraction[EXPONENT_WIDTH+1+FRACTION_WIDTH]='\0';

    Created_FP->Exponent_INT=binary2INT(Created_FP->Exponent,EXPONENT_WIDTH);
    Created_FP->Fraction_INT=binary2INT(Created_FP->Fraction,FRACTION_WIDTH);
    
    return Created_FP;
}
int binary2INT(char InChar[], int BitWidth){
    int i=0;
    int out=0;

    while(InChar[i]!='\0'){
        out+=(InChar[i]-48)*pow(2,(BitWidth-1-i));
        i++;
    }

    return out;
}

char *INT2binary(int InInT, int BitWidth){
    int i=2;
    int Quotient;
    int Remainder;
    int Coefficient;

    char *out=(char *)malloc(sizeof(char)*(BitWidth+1));

    Quotient=InInT/2;
    Remainder=InInT-Quotient*2;
    InInT=Quotient;
    Coefficient=Remainder;
    out[BitWidth-1]=Coefficient+48;


    do {
        Quotient=InInT/2;
        Remainder=InInT-Quotient*2;
        InInT=Quotient;
        Coefficient=Remainder;
        out[BitWidth-i]=Coefficient+48;
        i++;
    }while(Quotient!=0);

    while(BitWidth-i>=0){
        out[BitWidth-i]=48;
        i++;
    }

    out[BitWidth]='\0';
    printf("The converted Base 2 is: %s\n", out);
    return out;
}
/************************************************************************
 * Wrapper for malloc
 ************************************************************************/

void *FPmalloc(unsigned Size) {
  void *aPointer;

  if((aPointer = (void*) malloc(Size)) != NULL) return aPointer;
  else {
    printf("***** ERROR: Out of memory ***** \n");
    exit(0);
    return 0;
  }
}